﻿using AutoMapper;
using BackData;
using Domain.BOM;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.BOM;

namespace Team.API.Applocation.Hanldler.BOM
{
    public class GetBOMHandler:IRequestHandler<GetBOMCommand, APIPaging<Bomtable>>
    {
        private readonly IRepository<Bomtable> bomway;
        private readonly IMapper mapper;
        private readonly ILogger<GetBOMHandler> log;

        public GetBOMHandler(IRepository<Bomtable> bomway,IMapper mapper, ILogger<GetBOMHandler> log)
        {
            this.bomway = bomway;
            this.mapper = mapper;
            this.log = log;
        }
        /// <summary>
        /// 获取物料清单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<Bomtable>> Handle(GetBOMCommand request, CancellationToken cancellationToken)
        {
            var result = new APIPaging<Bomtable>();
            
            try
            {
                // 基础查询：未删除的BOM成品分层列表
                var query = bomway.GetAll().Where(x =>x.Category=="成品"&&  x.IsDel == false);

                // 成品编码筛选（物品编号）
                if (!string.IsNullOrWhiteSpace(request.Itemcode))
                {
                    query = query.Where(x => x.Itemcode != null && x.Itemcode.Contains(request.Itemcode));
                }

                // 成品名称筛选（物料名称）
                if (!string.IsNullOrWhiteSpace(request.GoodsName))
                {
                    query = query.Where(x => x.Goodsname != null && x.Goodsname.Contains(request.GoodsName));
                }

                // BOM编号筛选（物料清单版本）
                if (!string.IsNullOrWhiteSpace(request.BOMNumber))
                {
                    query = query.Where(x => x.Version != null && x.Version.Contains(request.BOMNumber));
                }

                // 状态筛选（是否使用）
                if (request.IsUse.HasValue)
                {
                    query = query.Where(x => x.IsUse == request.IsUse.Value);
                }

                // 获取总数
                var totalCount = query.Count();

                if (totalCount > 0)
                {
                    // 分页查询
                    var list = query
                        .OrderByDescending(x => x.Id)
                        .Skip((request.Pageindex - 1) * request.Pagesize)
                        .Take(request.Pagesize)
                        .ToList();

                    result.Totalcount = totalCount;
                    result.Code = StateCode.OK;
                    result.Message = "BOM列表获取成功";
                    result.ListResult = list;
                }
                else
                {
                    result.Totalcount = 0;
                    result.Code = StateCode.OK;
                    result.Message = "未找到符合条件的BOM数据";
                    result.ListResult = new List<Bomtable>();
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex, "获取BOM列表时发生错误");
                result.Code = StateCode.Fail;
                result.Message = "BOM列表获取失败：" + ex.Message;
                result.ListResult = new List<Bomtable>();
            }

            return Task.FromResult(result);
        }


    }
}
